#include "photoview.h"
#include <QFileInfo>
#include "common.h"
#include <QHBoxLayout>
#include <QApplication>
#include <QBitmap>

int PhotoView::m_id = qRegisterMetaType<PhotoView*>();

PhotoView::PhotoView(QWidget *parent)
    :ViewObject(parent)
    ,m_label(NULL)
    ,m_movie(NULL)
    ,hq_movie(NULL)
    ,m_paramIdentity(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose);
    m_label = new QLabel(this);
    m_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(m_label, 0, Qt::AlignCenter);
    layout->setContentsMargins(0, 0, 0, 0);
    setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
    {
       m_objectParam = new ParamObject;
    }

    if(m_paramIdentity == NULL)
    {
        m_paramIdentity = new PhotoViewParam;
    }
}

PhotoView::~PhotoView()
{
    DestoryObject();
}

void PhotoView::ShowObject(QWidget* parent, QString prefix, ProtocolData* ptr_data)
{
    Q_UNUSED(ptr_data);
    if (m_paramIdentity == NULL)
    {
        return;
    }
    if (m_objectParam == NULL)
    {
        return;
    }
    setParent(parent);
    m_label->clear();

    QString url = m_paramIdentity->m_resNormalPath;
    url = url.contains(";") == true ? url.left(url.size() -1) : url;

    //因为小火车采用photoview的形式，需要根据key_position去判断并切换照片
    if (ptr_data && ptr_data->key_position == 2)
    {
        if (url == "car_tc1")
            url = "car_tc2";
        if (url == "car_tc1_mirror")
            url = "car_tc2_mirror";
    }

    mPrefix = prefix;

#ifdef __WIN32__
    if (mPrefix == "")
        mPrefix = QString("%1/res/img/").arg(myapp::mDynamicMapParam->m_project_path);
#endif



//    if (ptr_data)
//    {
//        add_suffix(url, ptr_data->suffix);
//    }

    bool change = false;
    int change_x = 0;
    int change_y = 0;
    int change_w = 0;
    int change_h = 0;

    if (ptr_data)
    {
        for (auto it = ptr_data->items_change.begin(); it != ptr_data->items_change.end(); it++)
        {
            if (!it.key().compare(m_objectParam->GetName()))
            {
                change = true;

                if (it.value().x != DEFAULTVAL)
                {
                    change_x = it.value().x;
                }
                else
                {
                    change_x = m_objectParam->GetX();
                }
                if (it.value().y != DEFAULTVAL)
                {
                    change_y = it.value().y;
                }
                else
                {
                    change_y = m_objectParam->GetY();
                }
                if (it.value().w != DEFAULTVAL)
                {
                    change_w = it.value().w;
                }
                else
                {
                    change_w = m_objectParam->GetWidth();
                }
                if (it.value().h != DEFAULTVAL)
                {
                    change_h = it.value().h;
                }
                else
                {
                    change_h = m_objectParam->GetHeight();
                }
                if (it.value().content != "")
                {
                    url = it.value().content;
                }
            }
        }
    }

    url = myapp::find_file(mPrefix, url);

    if (url != "")
    {
        if (ptr_data && ptr_data->suffix != "")
        {
            QString url_contain_suffix = url.left(url.size() - 4) + QString("_") + QString(ptr_data->suffix) + url.right(4);
            if (myapp::find_file_single(mPrefix, url_contain_suffix) != "")
                url = url_contain_suffix;
        }
        url.push_front(mPrefix);

        //LOG_QDEBUG << "photo-------" << url;

        if ("hqv" == url.right(3))
        {
            if (myapp::isDirExist(url))
            {
                if (hq_movie == NULL)
                {
                    hq_movie = new HuaqiMovie(this);
                    if (NULL == hq_movie)
                        return;
                }
                else
                {
                    hq_movie->stop();
                }

                hq_movie->setFileName(url);
                QStringList list = hq_movie->getImageList();
                if (list.count() < 0)
                    return;

                m_label->setFixedSize(QSize(m_objectParam->GetWidth(), m_objectParam->GetHeight()));
                hq_movie->setLabel(m_label);
                hq_movie->start();

#ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
#endif
            }
        }
        else
        {
            // 解决设置gif图片之前设置过hqv资源，会继续显示hqv资源
            if (NULL != hq_movie)
            {
                hq_movie->stop();
                hq_movie->setLabel(NULL);
            }

            if ("gif" == url.right(3))
            {
                if (NULL == m_movie)
                {
                    m_movie = new QMovie(url, QByteArray(), this);
                    if (NULL == m_movie)
                        return;
                }
                else
                {
                    m_movie->stop();
                }
                m_movie->setFileName(url);
                m_movie->start();
                m_movie->setScaledSize(QSize(m_objectParam->GetWidth(), m_objectParam->GetHeight()));
                m_label->setMovie(m_movie);

                if (m_objectParam->GetStIdType() == STR_TRAIN)
                {
                   connect(m_movie, &QMovie::frameChanged, this, &PhotoView::StopGifEnd);
                }
#ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
#endif
            }
            else
            {
                QPixmap pixmap(url);
                m_label->setPixmap(pixmap);
#ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
#endif
            }

        }
    }
    else
    {
        m_label->setText(m_objectParam->GetObjectName());
    }

    if (change)
    {
        location(change_x, change_y, change_w, change_h);
    }
    else
    {
        location(m_objectParam->GetX(), m_objectParam->GetY(),
                    m_objectParam->GetWidth(), m_objectParam->GetHeight());
    }

    m_label->setFixedSize(size());
    show();
}

void PhotoView::StopGifEnd(int frame)
{
    if (m_movie == NULL)
        return;

    int frame_count = m_movie->frameCount();
    if (frame == frame_count - 1)
    {
        m_movie->stop();
        emit signalGifEnd();
    }
}

void PhotoView::HideObject()
{
    setParent(NULL);
    if (NULL != m_movie)
    {
        m_movie->stop();
    }
    hide();
}

void PhotoView::DestoryObject()
{
    HideObject();
    if (m_paramIdentity != NULL)
    {
        delete m_paramIdentity;
    }

    if (m_objectParam != NULL)
    {
        delete  m_objectParam;
    }
    m_paramIdentity = NULL;
    m_objectParam = NULL;

    close();
}

void PhotoView::GetAttribute(std::string& attribute)
{
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["idtype"] = m_objectParam->GetStIdType().toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();
    base["normal"] = m_paramIdentity->m_resNormalPath.toStdString();

    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void PhotoView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if(CheckJsonValueType(root,"zindex",Json::stringValue))
    {
         m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"stid",Json::stringValue))
    {
         m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"x",Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"y",Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"w",Json::stringValue))
    {
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"h",Json::stringValue))
    {
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"name",Json::stringValue))
    {
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }

    if(CheckJsonValueType(root,"normal",Json::stringValue))
    {
        m_paramIdentity->m_resNormalPath = QString::fromStdString(root["normal"].asString());
    }
    if(CheckJsonValueType(root,"idtype",Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));
    }
}

void PhotoView::ParseXML(QDomElement* xmlDomEle)
{
    if (NULL == m_paramIdentity)
    {
        m_paramIdentity = new PhotoViewParam;
    }
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));

    QDomNodeList paramlist = xmlDomEle->childNodes();
    for(int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if(param.isComment()||param.isNull())
        {
            continue;
        }
        QString temp = param.attribute("normal", "");
        if(temp != "")
        {
           m_paramIdentity->m_resNormalPath = temp;
        }
        temp = param.attribute("idtype", "");
        if(temp != "")
        {
            m_objectParam->SetStIdType(temp);
        }
    }
}

void PhotoView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type",m_objectParam->GetObjectName());
    dom->setAttribute("zindex", QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid", QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x", QString::number(m_objectParam->GetX()));
    dom->setAttribute("y", QString::number(m_objectParam->GetY()));
    dom->setAttribute("w", QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h", QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name", m_objectParam->GetName());

    QDomElement dom1 = document.createElement("param");
    dom1.setAttribute("idtype", m_objectParam->GetStIdType());
    dom->appendChild(dom1);

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("normal", m_paramIdentity->m_resNormalPath);
    dom->appendChild(dom2);
}

